package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.service.CommissionService;
import com.example.service.OrderService;
import com.example.service.UserService;
import com.example.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 分销
 * @author: xxx
 * @create: 2021/7/19 09:30
 */
@RestController
@RequestMapping("distribution")
public class DistributionController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private CommissionService commissionService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    Lock lock = new ReentrantLock();
    /**
     * @description: 我的粉丝
     * @param json
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("myFans")
    public Result myFans(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        jsonObject.put("pid",TokenTool.getUserId());
        Page.getPage(jsonObject);
        List<Map<String, Object>> mapList = userService.getListNew(jsonObject);
        int total = userService.getCountNew(jsonObject);
        Map<String, Map<String, Object>> mapNew = new HashMap<>();
        if (mapList != null && mapList.size()>0){
            List<String> ids = new ArrayList<>();
            for (Map<String, Object> mapUser : mapList) {
                ids.add(mapUser.get("id").toString());
                mapUser.put("priceSum",0);
                mapUser.put("priceBuy",0);
                mapUser.put("priceSale",0);
                mapNew.put(mapUser.get("id").toString(),mapUser);
            }
            List<Map<String, Object>> listPrice = orderService.getListPrice(ids);

            for (Map<String, Object> objectMap : listPrice) {
                if (mapNew.get(objectMap.get("buyerId").toString()) != null){
                    mapNew.get(objectMap.get("buyerId").toString()).put("priceSum",objectMap.get("priceSum"));
                }
            }
            List<Map<String, Object>> listFansListBuy = orderService.getFansListBuy(ids);
            for (Map<String, Object> objectMap : listFansListBuy) {
                if (mapNew.get(objectMap.get("buyerId").toString()) != null){
                    mapNew.get(objectMap.get("buyerId").toString()).put("priceBuy",objectMap.get("priceSum"));
                }
            }
            List<Map<String, Object>> listFansListSale = orderService.getFansListSale(ids);
            for (Map<String, Object> objectMap : listFansListSale) {
                if (mapNew.get(objectMap.get("buyerId").toString()) != null){
                    mapNew.get(objectMap.get("buyerId").toString()).put("priceSale",objectMap.get("priceSum"));
                }
            }
        }
        return ResultUtil.successPage(mapList,total);
    }
    /**
     * @description: 推广佣金
     * @param
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getCommissionList")
    public Result getCommissionList(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
//        jsonObject.put("pid","d4816508fbc94e7d8c54ba3853f1ad81");
        Page.getPage(jsonObject);
        jsonObject.put("pid", TokenTool.getUserId());
        List<Map<String, Object>> list = orderService.getCommissionList(jsonObject);
        int total = orderService.getCommissionCount(jsonObject);
        BigDecimal money = new BigDecimal(0d);
        Map<String, Object> newMap = new HashMap<>();
        newMap.put("pid",TokenTool.getUserId());
        Map<String, Object> mapSumMoney = orderService.getSumMoney(newMap);

        if (mapSumMoney != null){
            Double sumMoney = Double.parseDouble(mapSumMoney.get("sumMoney").toString());
            money = new BigDecimal(sumMoney).multiply(new BigDecimal(0.001)).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        return ResultUtil.successPageNew(list,total,money);

    }

    /**
     * @description: 获取账号佣金详情
     * @param map
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getMyCommission")
    public Result getMyCommission(@RequestBody Map<String,Object> map) {
        map.put("id", TokenTool.getUserId());

        return ResultUtil.success(commissionService.getById(map));
    }
    /**
     * @description: 获取购买记录
     * @param json
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
//    @RequestMapping("orderList")
//    public Result orderList(@RequestBody String json) {
//
//        JSONObject jsonObject = JSON.parseObject(json);
//        jsonObject.put("status", "1");
//        if (jsonObject.get("type").toString().equals("1")){
//            jsonObject.put("buyerId",TokenTool.getUserId());
//        }else if(jsonObject.get("type").toString().equals("2")){
//            jsonObject.put("userId",TokenTool.getUserId());
//        }else{
//            jsonObject.put("buyerId",TokenTool.getUserId());
//            jsonObject.put("status", "2");
//        }
//        jsonObject.remove("type");
//
//        jsonObject.put("studioId", TokenTool.getStudioId());
//        Page.getPage(jsonObject);
//        List<Map<String, Object>> list = service.getList(jsonObject);
//        int total = service.getCount(jsonObject);
//        return ResultUtil.successPage(list,total);
//    }
    /**
     * @description: 发起提现
     * @param
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("saveWithdraw")
    public Result saveWithdraw(@RequestBody Map<String,Object> map) {
            String paymentCode = map.get("paymentCode").toString();
            if (redisUtil.get("withdraw:"+TokenTool.getUserId()) != null){
                return ResultUtil.error(-500,"一周只允许提现一次");
            }else{

                Map<String,Object> mapNew = new HashMap<>();
                mapNew.put("id",TokenTool.getUserId());
                Map<String, Object>  userInfo = userService.getById(mapNew);
                Map<String,Object> mapCommission = commissionService.getById(mapNew);
                if (Double.parseDouble(map.get("money").toString()) <= Double.parseDouble(mapCommission.get("money").toString())){
                    if (DigestUtils.md5DigestAsHex(paymentCode.getBytes()).equals(userInfo.get("paymentCode").toString())){
                        map.put("id",IDTool.getUUID32());
                        map.put("userId",TokenTool.getUserId());
//                        map.put("studioId",TokenTool.getStudioId());
                        commissionService.saveWithdraw(map);
                        redisUtil.set("withdraw:"+TokenTool.getUserId(),"1",7L, TimeUnit.DAYS);
                    }else{
                        return ResultUtil.error(-500,"密码错误");
                    }
                }else{
                    return ResultUtil.error(-500,"余额不足");
                }

            }


        return ResultUtil.success();
    }
    /**
     * @description: 提现记录
     * @param
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getWithdrawPage")
    public Result getWithdrawPage(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        jsonObject.put("userId",TokenTool.getUserId());
        Page.getPage(jsonObject);
        List<Map<String, Object>> list = commissionService.getWithdrawList(jsonObject);
        int total = commissionService.getWithdrawCount(jsonObject);

        return ResultUtil.successPage(list,total);

    }
}
